package com.kr.aia.powerrp;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.kr.aia.powerrp.closing.ClosingMain;
import com.kr.aia.powerrp.common.MainMovieClipListView;
import com.kr.aia.powerrp.db.MySQLiteHelper;
import com.kr.aia.powerrp.dropbox.DropBoxMain;
import com.kr.aia.powerrp.roleplay.RPMain;
import com.kr.aia.powerrp.telephone.TAMain;
import com.kr.aia.powerrp.R;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.util.LruCache;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
	public static final String TAG = "PowerRP";
	
    private Button mcList = null;
    private Button btn_ta_main = null;
    private Button btn_rp_main = null;
    private Button btn_closing_main = null;
    private Button btn_manual_main = null;
    private Button btn_main_dropbox = null;
    
    AlertDialog dialog;
        
    MainMovieClipListView mcv;
    
    MySQLiteHelper dbHelper;
    SQLiteDatabase database;
    ProgressDialog initDialog;
    
    private LruCache<String, Bitmap> mMemoryCache;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        initDialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
        new dbCreationTask().execute(this);
        
        btn_ta_main = (Button)findViewById(R.id.btn_ta_main);
        btn_ta_main.setOnClickListener(this);
        
        btn_rp_main = (Button)findViewById(R.id.btn_rp_main);
        btn_rp_main.setOnClickListener(this);
        
        btn_closing_main = (Button)findViewById(R.id.btn_closing_main);
        btn_closing_main.setOnClickListener(this);
        
        btn_manual_main = (Button)findViewById(R.id.btn_manual_main);
        btn_manual_main.setOnClickListener(this);
        
        btn_main_dropbox = (Button)findViewById(R.id.btn_main_dropbox);
        btn_main_dropbox.setOnClickListener(this);
        
        
        mcList = (Button)findViewById(R.id.btn_view_movieclip);
        mcList.setOnClickListener(this);
        
        
        //btn_ta_main.setOnTouchListener(new commonOnTouchListener());
        //btn_rp_main.setOnTouchListener(new commonOnTouchListener());
        //btn_closing_main.setOnTouchListener(new commonOnTouchListener());
        //btn_manual_main.setOnTouchListener(new commonOnTouchListener());
        //mcList.setOnTouchListener(new commonOnTouchListener());
        
        
        final int memClass = ((ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();

        // Use 1/8th of the available memory for this memory cache.
        final int cacheSize = 1024 * 1024 * memClass / 8;

        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            /*
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // The cache size will be measured in bytes rather than number of items.
                return bitmap.getByteCount();
            }
            */
        };
    }
    
    public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemCache(key) == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    public Bitmap getBitmapFromMemCache(String key) {
        return mMemoryCache.get(key);
    }
    
    
    @Override
    public void onClick(View v){
    	switch(v.getId()){
    		case R.id.btn_view_movieclip:
    			AlertDialog.Builder builder = new AlertDialog.Builder(this);
    			
    		    mcv = new MainMovieClipListView(this, "");
    			View mcvView = mcv.openMovieClipListView();
    			
    			//.setIcon(R.drawable.icon_sja)		// icon 지정 후 Builder 객체 리턴
    			builder.setTitle("동영상 목록")				// title 지정
		   		//.setMessage("메시지 영역")			// 메시지 text 지정
		   		.setView(mcvView)	// 커스텀 뷰 지정
		   		// AlertDialog의 버튼 생성 & 버튼 클릭 이밴트에 대한 Listener 객체 생성/등록 
		   		.setPositiveButton("동영상 보기", new DialogInterface.OnClickListener()
			        {
			            @Override
			            public void onClick(DialogInterface dialog, int which)
			            {
			                //Do nothing here because we override this button later to change the close behaviour. 
			                //However, we still need this because on older versions of Android unless we 
			                //pass a handler the button doesn't get instantiated
			            }
			        })
		   		.setNegativeButton("닫기", new DialogInterface.OnClickListener(){
		   			@Override
					public void onClick(DialogInterface dialog, int which) {
		   				dialog.dismiss();
		   			}
		   		});
    			dialog = builder.create();
    			dialog.show(); // 지금까지 설정한 dialog를 화면에 보이고 AlertView객체를 return
    			
    			dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener(){            
    				@Override
    				public void onClick(View v){
		        	  	if(mcv.getIntentUri() != null){
							Intent intent = new Intent();
							intent.setAction(Intent.ACTION_VIEW);
							intent.setDataAndType(mcv.getIntentUri(), "video/mp4");
							startActivity(intent);
    		  			}else{
    		  				Toast.makeText(getApplicationContext(), "동영상을 선택하세요.", Toast.LENGTH_SHORT).show();
    		  			}
    				}
    			});

    			
    			break;
    		case R.id.btn_ta_main:
    			btn_ta_main.setAlpha(0.5f);
    			btn_ta_main.setEnabled(false);
    			Intent ta_intent = new Intent(this, TAMain.class);
    			//startActivity(ta_intent);
    			
    			startActivityForResult(ta_intent, 500);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    			break;
    		case R.id.btn_rp_main:
    			btn_rp_main.setAlpha(0.5f);
    			btn_rp_main.setEnabled(false);
    			Intent rp_intent = new Intent(this, RPMain.class);
    			//startActivity(rp_intent);
    			
    			startActivityForResult(rp_intent, 500);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    			break;
    		case R.id.btn_closing_main:
    			btn_closing_main.setAlpha(0.5f);
    			btn_closing_main.setEnabled(false);
    			Intent closing_intent = new Intent(this, ClosingMain.class);
    			//startActivity(closing_intent);
    			
    			startActivityForResult(closing_intent, 500);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    			break;
    		case R.id.btn_manual_main:
    			btn_manual_main.setAlpha(0.5f);
    			btn_manual_main.setEnabled(false);
    			//Intent manual_intent = new Intent(this, ManualMain.class);
    			//startActivity(manual_intent);
    			//startActivityForResult(manual_intent, 500);
                //overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    			
    			AssetManager assetManager = getAssets();

                InputStream in = null;
                OutputStream out = null;
                File file = new File(getFilesDir(), "Role_Play_Manual.pdf");
                try
                {
                    in = assetManager.open("Role_Play_Manual.pdf");
                    out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

                    copyFile(in, out);
                    in.close();
                    in = null;
                    out.flush();
                    out.close();
                    out = null;
                } catch (Exception e)
                {
                    Log.e("tag", e.getMessage());
                }

                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(
                        Uri.parse("file://" + getFilesDir() + "/Role_Play_Manual.pdf"),
                        "application/pdf");

                startActivity(intent);
    			
    			break;
    		case R.id.btn_main_dropbox:
    			Intent dropbox_intent = new Intent(this, DropBoxMain.class);
    			startActivityForResult(dropbox_intent, 500);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    			
    		default:
    			break;
    	}
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }
    
    @Override
    public void onResume(){
    	super.onResume();
    	btn_ta_main.setAlpha(1.0f);
    	btn_ta_main.setEnabled(true);
		
    	btn_rp_main.setAlpha(1.0f);
    	btn_rp_main.setEnabled(true);
		
    	btn_closing_main.setAlpha(1.0f);
    	btn_closing_main.setEnabled(true);
		
    	btn_manual_main.setAlpha(1.0f);
		btn_manual_main.setEnabled(true);
    }
    
    private class dbCreationTask extends AsyncTask<Context, Void, Void> {
		@Override
		protected Void doInBackground(Context... arg) {
			// TODO Auto-generated method stub
			dbHelper = new MySQLiteHelper(arg[0]);
	        database = dbHelper.getWritableDatabase();
	        dbHelper.createDatabase(database);
			return null;
		}
		
		@Override
		protected void onPostExecute(Void v) {
			dbHelper.close();
			if(initDialog.isShowing())
        		initDialog.dismiss();
		}
    }
    
    private void copyFile(InputStream in, OutputStream out) throws IOException
    {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1)
        {
            out.write(buffer, 0, read);
        }
    }
    

    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        menu.add(0, 0, 0, "StartRecording");
        menu.add(0, 1, 0, "StopRecording");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
        case 0:
            try {
            	preview.startRecording();
            } catch (Exception e) {
                String message = e.getMessage();
                Log.i(null, "Problem Start"+message);
                //mrec.release();
                preview.releaseMediaRecorder();
            }
            break;

        case 1: //GoToAllNotes
//            mrec.stop();
//            mrec.release();
//            mrec = null;
        	preview.stopRecording();
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }
    */

}